use std::{net::TcpStream, io::{Write, Read}};

fn main() {
    // client
    let mut stream = TcpStream::connect("127.0.0.1:8888").unwrap();
    let data = pack(0, String::from("hello").as_bytes().to_vec());
    stream.write(data.as_slice()).unwrap();
    let mut buf = [0u8;128];
    let len = stream.read(&mut buf).unwrap();
    println!("received {}", String::from_utf8_lossy(&buf[0..len]));

    let data = pack(0, String::from("hi").as_bytes().to_vec());
    stream.write(data.as_slice()).unwrap();
    let mut buf = [0u8;128];
    let len = stream.read(&mut buf).unwrap();
    println!("received {}", String::from_utf8_lossy(&buf[0..len]));
}

pub struct Message {
    pub id:u32,
    pub len:u32,
    pub data:Vec<u8>,
}

pub fn parse_header(header:[u8;8]) -> (u32, u32) {
    ((header[0] as u32) << 24 | (header[1] as u32) << 16 | (header[2] as u32) << 8 | header[3] as u32, (header[0] as u32) << 24 | (header[1] as u32) << 16 | (header[2] as u32) << 8 | (header[3] as u32))
}

pub fn serialize_header(id:u32,len:u32) -> [u8;8] {
    [(id >> 24) as u8, (id >> 16) as u8, (id >> 8) as u8, id as u8, (len >> 24) as u8, (len >> 16) as u8, (len >> 8) as u8, len as u8]
}

pub fn serialize_vec_header(id:u32,len:u32) -> Vec<u8> {
    vec![(id >> 24) as u8, (id >> 16) as u8, (id >> 8) as u8, id as u8, (len >> 24) as u8, (len >> 16) as u8, (len >> 8) as u8, len as u8]
}

pub fn pack(id:u32, mut data:Vec<u8>) -> Vec<u8> {
    let mut header = serialize_vec_header(id, data.len() as u32);
    header.append(&mut data);
    header
}